package com.jinzhi.jzweb.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.dao.JazCoursesOrderDao;
import com.jinzhi.jzweb.dao.JazUserHouseDao;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.vo.JazUserOrderQueryVo;
import com.jinzhi.jzweb.domain.vo.JazUserOrderVO;
import com.jinzhi.jzweb.domain.vo.home.OrderRechargeVo;
import com.jinzhi.jzweb.domain.vo.userAunt.UserVO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxpay.service.OrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazUserOrderDao;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2023-04-18 09:38:41 | Long</small>
 */

@Service
@Component
public class JazUserOrderServiceImpl extends CoreServiceImpl<JazUserOrderDao, JazUserOrderDO> implements JazUserOrderService {
    @Autowired
    JazUserOrderDao jazUserOrderDao;

    @Autowired
    private UserService userService;

    @Autowired
    private JazUserOrderService jazUserOrderService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private JazGroupOrderService jazGroupOrderService;

    @Autowired
    private JazSysContractService jazSysContractService;

    @Autowired
    private JazSysContractTemplateService jazSysContractTemplateService;

    @Autowired
    private JazSysProjectService jazSysProjectService; //服务表

    @Autowired
    private JazMessageService jazMessageService;

    @Autowired
    private JazCoursesOrderDao jazCoursesOrderDao;

    @Autowired
    private JazGroupSpecsService jazGroupSpecsService;

    private final JazUserRechargeService jazUserRechargeService;

    private final JazUserAuntService jazUserAuntService;

    private final JazUserDemandService jazUserDemandService;

    @Autowired
    private JazUserIntegralService jazUserIntegralService; //积分明细表
    @Autowired
    private JazUserHouseService jazUserHouseService;
    @Autowired
    private JazBedNumberService jazBedNumberService;

    @Autowired
    private JazHouseTypesService jazHouseTypesService;

    @Autowired
    private JazUserHouseDao jazUserHouseDao;

    private final JazProdTypeService jazProdTypeService;

    int contractConclude = 2000; //签合同所需积分



    public JazUserOrderServiceImpl(JazUserRechargeService jazUserRechargeService, JazUserAuntService jazUserAuntService, JazUserDemandService jazUserDemandService, JazProdTypeService jazProdTypeService) {
        this.jazUserRechargeService = jazUserRechargeService;
        this.jazUserAuntService = jazUserAuntService;
        this.jazUserDemandService = jazUserDemandService;
        this.jazProdTypeService = jazProdTypeService;
    }

    /**
     * 查询服务订单列表
     * @return
     */
    @Override
    public Page<JazUserOrderVO> selectOrderList(JazUserOrderQueryVo jazUserOrderQueryVo) {
        Page<JazUserOrderVO> page = new Page<>(jazUserOrderQueryVo.getCurrent(), jazUserOrderQueryVo.getSize());

        // 查询服务订单
        List<JazUserOrderVO> jazUserOrderDOS = jazUserOrderDao.selectOrderList(page,jazUserOrderQueryVo);
        // 剔除数据
        for (int i = 0; i < jazUserOrderDOS.size(); i++) {
            if (jazUserOrderDOS.get(i).getStatus()==null){
                jazUserOrderDOS.remove(i);
            }
        }

        // 团购数据添加阿姨信息
        jazUserOrderDOS.stream().forEach(jazUserOrderVO -> {
            // 设置阿姨信息
            UserDO userDO = userService.selectById(jazUserOrderVO.getSigningId());
            if (null!=userDO){
                if (StringUtil.notEmpty(userDO.getName())){
                    jazUserOrderVO.setNameYi(userDO.getName());
                }else {
                    jazUserOrderVO.setNameYi(userDO.getUsername());
                }
                if (StringUtil.notEmpty(userDO.getOrderPhone())) {
                    jazUserOrderVO.setPhoneYi(userDO.getOrderPhone());
                }else {
                    jazUserOrderVO.setPhoneYi(userDO.getMobile());
                }
            }
            // 设置团购名称
            if (jazUserOrderVO.getJazProdTypeId()!=null){
                JazProdTypeDO jazProdTypeDO = jazProdTypeService.selectById(jazUserOrderVO.getJazProdTypeId());
                if (null!=jazProdTypeDO){
                    jazUserOrderVO.setJazProdTypeName(jazProdTypeDO.getName());
                }
            }
            // 设置创建时间
            jazUserOrderVO.setCreateTime(jazUserOrderVO.getCreateTime().replace(".0",""));
            //查询项目类型
            if(StringUtil.notEmpty(jazUserOrderVO.getProjectId())){
                String[] projects = jazUserOrderVO.getProjectId().split(",");
                List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                jazUserOrderVO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
            }
            //查询商品详情
            if(null!=jazUserOrderVO.getOrderType()&&jazUserOrderVO.getOrderType()==1){
                JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(jazUserOrderVO.getProductId());
                jazUserOrderVO.setProductName(null==jazGroupSpecsDO?"":jazGroupSpecsDO.getName());
                //状态
                if(jazUserOrderVO.getStatus()==0||null==jazUserOrderVO.getAuditResult()){
                    //待审核
                    jazUserOrderVO.setAuditStatus("待审核");
                }else{
                    //判断是否审核auditResult
                    jazUserOrderVO.setAuditStatus(jazUserOrderVO.getAuditResult()==0?"审核通过":"审核拒绝");
                }
            }
        });

        page.setRecords(jazUserOrderDOS);
        return page;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public JazUserOrderVO selectOrderDetail(Long id) {
        //根据查询出订单信息
        JazUserOrderDO jazUserOrderDO = selectById(id);
        if (jazUserOrderDO == null){
            return null;
        }
        // 需求订单
        if (jazUserOrderDO.getOrderType()==2){
            return getJazUserOrderVO(jazUserOrderDO.getInitiateId(), jazUserOrderDO.getSigningId(), id, jazUserOrderDO);
        }else if(jazUserOrderDO.getOrderType()==1){
            //订单类型
//            JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserOrderDO.getProjectId());
//            if (jazSysProjectDO == null){
//                return null;
//            }
            // 团购订单
            Wrapper<JazGroupOrderDO> wrapper = new EntityWrapper<JazGroupOrderDO>().eq("order_no", jazUserOrderDO.getNumber());
            JazGroupOrderDO jazGroupOrderDO = jazGroupOrderService.selectOne(wrapper);
            if (jazGroupOrderDO!=null){
                UserDO userDO = userService.selectById(jazGroupOrderDO.getUserId());
                JazUserOrderVO jazUserOrderVO = new JazUserOrderVO();
                BeanUtils.copyProperties(jazUserOrderDO,jazUserOrderVO);
                //订单信息
                jazUserOrderVO.setId(id);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = formatter.format(jazUserOrderDO.getCreateTime());
                jazUserOrderVO.setCreateTime(formattedDate);
                jazUserOrderVO.setStartTime(formatter.format(jazUserOrderDO.getStartTime()));
                jazUserOrderVO.setEndTime(formatter.format(jazUserOrderDO.getEndTime()));
//                jazUserOrderVO.setProjectName(jazSysProjectDO.getName());
                jazUserOrderVO.setProjectName("");
                //发起人信息
                jazUserOrderVO.setName(userDO.getNickname());
                jazUserOrderVO.setMobile(userDO.getMobile());
                //签约人信息
                UserDO userDO1 = userService.selectById(jazUserOrderDO.getSigningId());
                if (userDO1 == null){
                    jazUserOrderVO.setNames(null);
                    jazUserOrderVO.setMobiles(null);
                }else {
                    jazUserOrderVO.setNames(userDO1.getName());
                    jazUserOrderVO.setMobiles(userDO1.getMobile());
                }
                //商品名称
                JazGroupSpecsDO jazGroupSpecsDO = jazGroupSpecsService.selectById(jazUserOrderVO.getProductId());
                jazUserOrderVO.setProductName(null==jazGroupSpecsDO?"":jazGroupSpecsDO.getName());

                return jazUserOrderVO;
            }

        }
        return null;
    }

    /**
     * 查询需求订单
     * @param initiateId
     * @param signingId
     * @param id
     * @param jazUserOrderDO
     * @return
     */
    private JazUserOrderVO getJazUserOrderVO(Long initiateId, Long signingId, Long id, JazUserOrderDO jazUserOrderDO) {
        //查询出订单创建人信息
        UserDO userDO1 = userService.selectById(initiateId);
        if (userDO1==null) {
            return null;
        }
        //查询出订单签约人信息
        UserDO user = userService.selectById(signingId);
        if (user==null) {
            return null;
        }
        //订单类型
        JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserOrderDO.getProjectId());
        if (jazSysProjectDO==null) {
            return null;
        }
        JazUserOrderVO jazUserOrderVO = new JazUserOrderVO();
        BeanUtils.copyProperties(jazUserOrderDO,jazUserOrderVO);
        //获取签约人姓名、电话号码
        //获取合同pdf路径  判断线上或线下签的合同
        if (jazUserOrderDO.getContractType()==0){
            JazSysContractTemplateDO jazSysContractTemplateDO = jazSysContractTemplateService.selectById(jazUserOrderDO.getContractId());
            if (jazSysContractTemplateDO==null) {
                return null;
            }
            // todo 封装合同地址
            //jazUserOrderVO.setContract(jazSysContractTemplateDO.getPdfPath());//合同
            //this.userOrderExport();
        }else {
            jazUserOrderVO.setContract(jazUserOrderDO.getContractNamePath());//合同
        }
        //订单信息
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jazUserOrderVO.setCreateTime(formatter.format(jazUserOrderDO.getCreateTime()));
        jazUserOrderVO.setStartTime(formatter.format(jazUserOrderDO.getStartTime()));
        jazUserOrderVO.setEndTime(formatter.format(jazUserOrderDO.getEndTime()));
        jazUserOrderVO.setProjectName(jazSysProjectDO.getName());
        //发起人信息
        jazUserOrderVO.setName(jazUserOrderDO.getNameJia());
        jazUserOrderVO.setMobile(userDO1.getMobile());
        jazUserOrderVO.setIdNumber(jazUserOrderDO.getIdentityCardJia());//甲方身份证号
        jazUserOrderVO.setDetailedAddress(jazUserOrderDO.getHomeAddressJia());//甲方家庭住址
        //签约人信息
        jazUserOrderVO.setNames(jazUserOrderDO.getNameYi());
        jazUserOrderVO.setMobiles(user.getMobile());
        jazUserOrderVO.setIdNumbers(jazUserOrderDO.getIdentityCardYi());//乙方身份证号码
        jazUserOrderVO.setDetailedAddress2(jazUserOrderDO.getHomeAddressYi());//乙方家庭住址
        return jazUserOrderVO;
    }

    /***
     * 查询所有保洁信息
     * @return
     */
    @Override
    public List<UserVO> getUserAunt(String id,String projectId) {
        List<UserVO> userVOList = new ArrayList<>();
        // 获取已通过审核的阿姨的信息
        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("audit_status",1).eq("audit_result",0).eq("enable_status",1));
        // 过滤相应类型的阿姨
        Set<String> projectIdsSet = Arrays.stream(projectId.split(","))
                .map(String::trim)
                .collect(Collectors.toSet());
        List<JazUserAuntDO> filteredList = jazUserAuntDOList.stream()
                // 过滤条件：jazUserAuntDO.getProjectId()中的每一个ID都在projectIdsSet中存在
                .filter(jazUserAuntDO -> {
                    Set<String> auntProjectIdsSet = Arrays.stream(jazUserAuntDO.getProjectId().split(","))
                            .map(String::trim)
                            .collect(Collectors.toSet());
                    return !Collections.disjoint(auntProjectIdsSet, projectIdsSet);  // 只包含一个id就能查出
                    //return projectIdsSet.containsAll(auntProjectIdsSet);  // 包含全部的id才能查出
                })
                .collect(Collectors.toList());
        // 判断是需求还是保洁
        if (id!=null){
            JazUserOrderDO jazUserOrderDO = this.selectById(id);
            if (jazUserOrderDO.getOrderType()==2) {
                Long signingId = jazUserOrderDO.getSigningId();
//                List<JazUserAuntDO> userAuntDOList = filteredList.stream()
//                        .filter(element -> !element.getSysUserid().equals(signingId))
//                        .collect(Collectors.toList());
//                extracted(userAuntDOList,userVOList);
                extracted(filteredList,userVOList);
                return userVOList;
            }else if (jazUserOrderDO.getOrderType()==1){
                // 获取所有的阿姨的用户表id
                extracted(filteredList, userVOList);
                return userVOList;
            }
        }
        return null;
    }

    /***
     * 查询所有保洁信息
     * @return
     */
    @Override
    public List<UserVO> getUserAuntBaoJie() {
        List<UserVO> userVOList = new ArrayList<>();
        // 获取已通过审核的阿姨的信息
        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("audit_status",1)
                .eq("audit_result",0)
                .eq("enable_status",1)
                .eq("signing_status",0));
        extracted(jazUserAuntDOList, userVOList);
        return userVOList;
    }


    /**
     * 阿姨端待开始服务订单数量
     * @return
     */
    @Override
    public Integer auntOrderStatusNum() {
        Long userId = JWTUtil.getUser().getId();
        return  this.selectCount(new EntityWrapper<JazUserOrderDO>().eq("signing_id", userId).eq("order_read_yi", 0).eq("status", 0));
    }

    /**
     * 阿姨端修改服务订单为已读 orderIds多个以逗号隔开
     * @param orderIds
     */
    @Override
    public void auntUpdateOrderRead(String orderIds) {
        Assert.notNull(orderIds,"参数：'orderIds'不能为空");
        List<String> idList = new ArrayList<>(Arrays.asList(orderIds.split(",")));
        JazUserOrderDO jazUserOrderDO = new JazUserOrderDO();
        jazUserOrderDO.setOrderReadYi(1);
        this.update(jazUserOrderDO,new EntityWrapper<JazUserOrderDO>().in("id",idList));
    }

    /**
     * 阿姨端待签署合同数量
     * @return
     */
    @Override
    public Integer auntConcludeStatusNum() {
        Long userId = JWTUtil.getUser().getId();
        return  this.selectCount(new EntityWrapper<JazUserOrderDO>().eq("signing_id", userId).eq("conclude_read_yi", 0).eq("conclude_status",1));
    }

    /**
     * 阿姨端修改合同为已读 orderIds多个以逗号隔开
     * @param orderIds
     */
    @Override
    public void auntUpdateConcludeRead(String orderIds) {
        Assert.notNull(orderIds,"参数：'orderIds'不能为空");
        List<String> idList = new ArrayList<>(Arrays.asList(orderIds.split(",")));
        JazUserOrderDO jazUserOrderDO = new JazUserOrderDO();
        jazUserOrderDO.setConcludeReadYi(1);
        this.update(jazUserOrderDO,new EntityWrapper<JazUserOrderDO>().in("id",idList));
    }


    /**
     * 封装月嫂或保洁信息
     * @param filteredList
     * @param userVOList
     */
    private void extracted(List<JazUserAuntDO> filteredList, List<UserVO> userVOList) {
        filteredList.forEach(userAunt->{
            UserVO userVO = new UserVO();
            UserDO userDO = userService.selectById(userAunt.getSysUserid());
            userVO.setSex(userDO.getSex());
            if (StringUtil.notEmpty(userDO.getName())){
                userVO.setName(userDO.getName());
            }
            userVO.setSysUserid(userDO.getId());
            if(StringUtil.notEmpty(userDO.getOrderPhone())){
                userVO.setMobile(userDO.getOrderPhone());
            }else {
                userVO.setMobile("");
            }
            userVO.setProjectId(userAunt.getProjectId());
            if(StringUtil.notEmpty(userDO.getIdNumber())){
                userVO.setIdNumber(userDO.getIdNumber());
            }else {
                userVO.setIdNumber("");
            }
            StringBuffer buffer = new StringBuffer();
            if (StringUtil.notEmpty(userDO.getProvince())){
                buffer.append(userDO.getProvince());
            }
            if (StringUtil.notEmpty(userDO.getCity())){
                buffer.append(userDO.getCity());
            }
            if (StringUtil.notEmpty(userDO.getDistrict())){
                buffer.append(userDO.getDistrict());
            }
            if (StringUtil.notEmpty(userDO.getDetailedAddress())){
                buffer.append(userDO.getDetailedAddress());
            }
            userVO.setAddress(buffer.toString());
            if(StringUtil.notEmpty(userAunt.getProjectId())){
                String[] projects = userAunt.getProjectId().split(",");
                List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                userVO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
            }
            userVOList.add(userVO);
        });
    }

    /**
     * 修改审核结果
     *
     * @param jazUserOrder
     * @return
     */
    @Override
    public Result<String> updateAuditResult(JazUserOrderDO jazUserOrder) {
        if (jazUserOrder==null){
            return Result.fail();
        }
        JazUserOrderDO jazUserOrderDO = this.selectById(jazUserOrder.getId());
        if (jazUserOrderDO!=null){
            jazUserOrderDO.setAuditResult(jazUserOrder.getAuditResult());
            if (jazUserOrder.getAuditResult()==1){
                if (StringUtil.notEmpty(jazUserOrder.getRejectReasion())){
                    jazUserOrderDO.setRejectReasion(jazUserOrder.getRejectReasion());
                }else {
                    return Result.fail("请输入拒绝原因");
                }
            }
            // 设置订单为已完成
            jazUserOrderDO.setStatus(2);
        }
        boolean update = this.updateById(jazUserOrderDO);
        return update?Result.ok():Result.fail();
    }

    /**
     * 服务转让
     *
     * @param jazUserOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result serviceTransfer(JazUserOrderVO jazUserOrder) {
        if (jazUserOrder==null){
            return Result.fail();
        }
        JazUserOrderDO jazUserOrderDO = this.selectById(jazUserOrder.getId());
        if (jazUserOrderDO==null){
            return Result.fail();
        }

        // 查询合同模版信息
//        JazSysContractTemplateDO jazSysContractTemplateDO = jazSysContractTemplateService.selectById(jazUserOrderDO.getContractId());
//        if (jazSysContractTemplateDO==null){
//            return Result.fail();
//        }

        // 更新原来的服务订单为已转让
        jazUserOrderDO.setStatus(4);
        jazUserOrderDO.setConcludeStatus(4);
        boolean update3 = this.updateById(jazUserOrderDO);
        if (!update3){
            throw new RuntimeException();
        }

        //旧的月嫂未上户
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>()
                .eq("sys_userid",jazUserOrderDO.getSigningId()));
        if (jazUserAuntDO == null){
            throw new RuntimeException();
        }
        jazUserAuntDO.setSigningStatus(0); //待签约
        jazUserAuntDO.setFamilyStatus(0); // 未上户
        boolean update = jazUserAuntService.updateById(jazUserAuntDO);
        if (!update){
            throw new RuntimeException();
        }

        // 创建一条新的服务订单
        JazUserOrderDO userOrderDO = new JazUserOrderDO();
        userOrderDO.setInitiateId(jazUserOrderDO.getInitiateId());
        userOrderDO.setSigningId(jazUserOrder.getSigningId());
        // 查询合同模版
        JazSysContractTemplateDO jazSysContractTemplateDO = jazSysContractTemplateService.selectOne(new EntityWrapper<JazSysContractTemplateDO>()
                .eq("project_id", jazUserOrder.getProjectId()));
        if (jazSysContractTemplateDO!=null){
            jazUserOrderDO.setContractId(jazSysContractTemplateDO.getId());
        }
        userOrderDO.setTotalPrice(jazUserOrderDO.getTotalPrice());
        userOrderDO.setRemark(jazUserOrder.getRemark());
        userOrderDO.setProjectId(jazUserOrder.getProjectId());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据你的日期时间格式进行修改
        try {
            userOrderDO.setStartTime(formatter.parse(jazUserOrder.getStartTime()));
            userOrderDO.setEndTime(formatter.parse(jazUserOrder.getEndTime()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        userOrderDO.setContractType(1); // 线下
        userOrderDO.setIdentityCardJia(jazUserOrder.getIdNumber());
        userOrderDO.setIdentityCardYi(jazUserOrder.getIdNumbers());
        userOrderDO.setNameJia(jazUserOrder.getName());
        userOrderDO.setNameYi(jazUserOrder.getNames());
        userOrderDO.setPhoneJia(jazUserOrder.getMobile());
        userOrderDO.setPhoneYi(jazUserOrder.getMobiles());
        userOrderDO.setRemark(jazUserOrder.getRemark());
        userOrderDO.setAddress(jazUserOrder.getAddress());
        userOrderDO.setHomeAddressJia(jazUserOrder.getDetailedAddress());
        userOrderDO.setHomeAddressYi(jazUserOrder.getDetailedAddress2());
        userOrderDO.setStatus(1);
        userOrderDO.setConcludeStatus(2); // 合同已签署状态
        userOrderDO.setSignSource("0");
        userOrderDO.setOrderType(2);
        userOrderDO.setNumber(tweenRandom());
        userOrderDO.setDemandId(jazUserOrderDO.getDemandId());
        userOrderDO.setContractId(jazUserOrderDO.getContractId());
        // 设置签名的合同地址
        userOrderDO.setContractNamePath(jazUserOrder.getContractNamePath());
        userOrderDO.setContractNameYiPath(jazUserOrder.getContractNameYiPath());
        // 甲方手写签名
        userOrderDO.setSignatureJia(jazUserOrderDO.getSignatureJia());
        boolean update1 = this.insert(userOrderDO);
        if (!update1){
            throw new RuntimeException();
        }

        // 新的月嫂已上户
        JazUserAuntDO jazUserAuntDO1 = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>()
                .eq("sys_userid",userOrderDO.getSigningId()));
        if (jazUserAuntDO1 == null){
            throw new RuntimeException();
        }
        jazUserAuntDO1.setFamilyStatus(1); // 已上户
        jazUserAuntDO1.setSigningStatus(1);//已签约
        boolean update4 = jazUserAuntService.updateById(jazUserAuntDO1);
        if (!update4){
            throw new RuntimeException();
        }

        // 禁止之前合同状态
        /*jazSysContractTemplateDO.setStatus(1);
        boolean update = jazSysContractTemplateService.updateById(jazSysContractTemplateDO);
        if (!update){
            return Result.fail();
        }*/

        // 添加新的合同信息
/*        JazSysContractTemplateDO contractDO = new JazSysContractTemplateDO();
        contractDO.setSysUserid(jazSysContractTemplateDO.getSysUserid());
        contractDO.setName(jazSysContractTemplateDO.getName());
        contractDO.setProjectId(jazUserOrder.getProjectId());
        contractDO.setPdfPath(jazUserOrder.getContract());
        contractDO.setStatus(0);
//        contractDO.setSignedUserId(jazUserOrder.getSigningId());
//        contractDO.setServiceTotalPrice(jazUserOrder.getTotalPrice());
//        contractDO.setServiceStartTime(jazUserOrder.getStartTime());
//        contractDO.setServiceEndTime(jazUserOrder.getEndTime());
        contractDO.setVersion("1");
        boolean update2 = jazSysContractTemplateService.insert(contractDO);
        if (!update2){
            return Result.fail();
        }*/

        if (update1) {
            // 发送消息通知
            // 新的服务人
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(1);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(userOrderDO.getSigningId());
            jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_212.getMsg());
            jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_212.getNum());
            jazMessageDO1.setHasSendSms(true);
            jazMessageDO1.setUserOrderId(userOrderDO.getId());
            jazMessageDO1.setIsRead(0);
            // 旧的服务人
            JazMessageDO jazMessageDO2 = new JazMessageDO();
            jazMessageDO2.setMessageType(2);
            jazMessageDO2.setSenderId(ShiroUtils.getUserId());
            jazMessageDO2.setReceiverId(jazUserOrderDO.getSigningId());
            jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_206.getMsg());
            jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_206.getNum());
            jazMessageDO2.setHasSendSms(true);
            jazMessageDO2.setUserOrderId(jazUserOrderDO.getId());
            jazMessageDO2.setIsRead(0);
            // 用户 userOrderDO.getSigningId()
            JazMessageDO jazMessageDO3 = new JazMessageDO();
            jazMessageDO3.setMessageType(1);
            jazMessageDO3.setSenderId(ShiroUtils.getUserId());
            jazMessageDO3.setReceiverId(jazUserOrderDO.getInitiateId());
            jazMessageDO3.setMessageContent(MessagesEnum.MESSAGE_205.getMsg());
            jazMessageDO3.setMessageNum(MessagesEnum.MESSAGE_205.getNum());
            jazMessageDO3.setIsRead(0);
            jazMessageService.senMessage(jazMessageDO1);
            jazMessageService.senMessage(jazMessageDO2);
            jazMessageService.senMessage(jazMessageDO3);
        }
        return update1?Result.ok() : Result.fail();
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result serviceTransferById(Long id) {
        JazUserOrderDO jazUserOrderDO = this.selectById(id);
        if (jazUserOrderDO==null){
            return Result.fail();
        }
        //查询出订单创建人信息
        UserDO userDO1 = userService.selectById(jazUserOrderDO.getInitiateId());
        //订单类型
        JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserOrderDO.getProjectId());
        //获取签约人姓名、电话号码
        JazUserOrderVO jazUserOrderVO = new JazUserOrderVO();
        BeanUtils.copyProperties(jazUserOrderDO,jazUserOrderVO);
        //订单信息
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jazUserOrderVO.setCreateTime(formatter.format(jazUserOrderDO.getCreateTime()));
        jazUserOrderVO.setStartTime(formatter.format(jazUserOrderDO.getStartTime()));
        jazUserOrderVO.setEndTime(formatter.format(jazUserOrderDO.getEndTime()));
        jazUserOrderVO.setProjectName(jazSysProjectDO.getName());
        //发起人信息
        jazUserOrderVO.setName(jazUserOrderDO.getNameJia());
        jazUserOrderVO.setMobile(userDO1.getMobile());
        jazUserOrderVO.setIdNumber(jazUserOrderDO.getIdentityCardJia());//甲方身份证号
        jazUserOrderVO.setDetailedAddress(jazUserOrderDO.getHomeAddressJia());//甲方家庭住址

        return Result.ok(jazUserOrderVO);
    }

    /**
     * 修改服务订单月嫂信息
     * @param jazUserOrderVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateUserOrderAunt(JazUserOrderVO jazUserOrderVO) {
        if (jazUserOrderVO==null){
            return Result.fail();
        }
        JazUserOrderDO jazUserOrderDO = this.selectById(jazUserOrderVO.getId());
        if (jazUserOrderDO==null){
            return Result.fail();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据你的日期时间格式进行修改
        try {
            jazUserOrderDO.setStartTime(formatter.parse(jazUserOrderVO.getStartTime()));
            jazUserOrderDO.setEndTime(formatter.parse(jazUserOrderVO.getEndTime()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        jazUserOrderDO.setAddress(jazUserOrderVO.getAddress());
        jazUserOrderDO.setTotalPrice(jazUserOrderVO.getTotalPrice());
        jazUserOrderDO.setSigningId(jazUserOrderVO.getSigningId());
        jazUserOrderDO.setRemark(jazUserOrderVO.getRemark());
        jazUserOrderDO.setPhoneYi(jazUserOrderVO.getMobiles());
        jazUserOrderDO.setIdentityCardYi(jazUserOrderVO.getIdNumbers());
        jazUserOrderDO.setNameYi(jazUserOrderVO.getNames());
        jazUserOrderDO.setHomeAddressYi(jazUserOrderVO.getDetailedAddress2());
        jazUserOrderDO.setProjectId(jazUserOrderDO.getProjectId());
        // 校验合同
        jazUserOrderDO.setContractType(1);
        jazUserOrderDO.setContractNamePath(jazUserOrderVO.getContract());// 用户合同
        jazUserOrderDO.setContractNameYiPath(jazUserOrderVO.getContractNameYiPath()); // 阿姨合同
        boolean update1 = this.updateById(jazUserOrderDO);
        // 合同
/*        if (StringUtil.notEmpty(jazUserOrderVO.getContract()) && jazUserOrderDO.getContractId()!=null){
            JazSysContractTemplateDO jazSysContractDO = jazSysContractTemplateService.selectById(jazUserOrderDO.getContractId());
            jazSysContractDO.setPdfPath(jazUserOrderVO.getContract());
            boolean update = jazSysContractTemplateService.updateById(jazSysContractDO);
            return update?Result.ok():Result.fail();
        }*/
        return update1?Result.ok():Result.fail();
    }


    /**
     * 服务列表续费
     *
     * @param jazUserOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> orderRenew(JazUserOrderDO jazUserOrder) {
        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(jazUserOrder.getId());
        if (jazUserOrderDO == null){
            return Result.fail();
        }
        // 判断订单状态
        if (jazUserOrderDO.getStatus()!=1){
            return Result.fail("订单不是在进行中，不能进行续费订单");
        }
        // 判断结束时间是否小于当前结束时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        if (simpleDateFormat.format(jazUserOrderDO.getEndTime().getTime())>=simpleDateFormat.format(jazUserOrder.getEndTime().getTime())){
//            return Result.fail("结束时间不能小于当前结束时间");
//        }
        // 获取两个日期的 "yyyy-MM-dd" 格式化的字符串表示
        String endTime1 = simpleDateFormat.format(jazUserOrderDO.getEndTime().getTime());
        String endTime2 = simpleDateFormat.format(jazUserOrder.getEndTime().getTime());

        // 将格式化的字符串重新解析为 Date 对象
        try {
            Date date1 = simpleDateFormat.parse(endTime1);
            Date date2 = simpleDateFormat.parse(endTime2);

            // 比较两个日期的大小
            if (date1.compareTo(date2) > 0) {
                return Result.fail("结束时间不能小于当前结束时间");
            }
        } catch (ParseException e) {
            // 处理解析异常
            e.printStackTrace();
            return Result.fail("日期格式错误");
        }
        StringBuffer buffer = new StringBuffer();
        // 历史用户合同
        if (StringUtil.notEmpty(jazUserOrderDO.getHistoryContractNamePath())){
            // 不是第一次续费
            buffer.append(jazUserOrderDO.getHistoryContractNamePath()).append(",").append(jazUserOrderDO.getContractNamePath());
            // 历史用户合同
            jazUserOrderDO.setHistoryContractNamePath(buffer.toString());
        }else {
            // 第一次续费
            jazUserOrderDO.setHistoryContractNamePath(jazUserOrderDO.getContractNamePath());
        }
        buffer=new StringBuffer();
        // 历史阿姨合同
        if (StringUtil.notEmpty(jazUserOrderDO.getHistoryContractNameYiPath())){
            buffer.append(jazUserOrderDO.getHistoryContractNameYiPath()).append(",").append(jazUserOrderDO.getContractNameYiPath());
            jazUserOrderDO.setHistoryContractNameYiPath(buffer.toString());
        }else {
            // 第一次续费
            jazUserOrderDO.setHistoryContractNameYiPath(jazUserOrderDO.getContractNameYiPath());
        }
        // 结束时间
        jazUserOrderDO.setEndTime(jazUserOrder.getEndTime());
        // 开始时间
        jazUserOrderDO.setStartTime(jazUserOrder.getStartTime());
        // 用户合同
        jazUserOrderDO.setContractNamePath(jazUserOrder.getContractNamePath());
        // 阿姨合同
        jazUserOrderDO.setContractNameYiPath(jazUserOrder.getContractNameYiPath());

        boolean update = jazUserOrderService.updateById(jazUserOrderDO);
        // 发送消息  阿姨
        JazMessageDO jazMessageDO1 = new JazMessageDO();
        jazMessageDO1.setMessageType(1); //系统消息
        jazMessageDO1.setSenderId(ShiroUtils.getUserId()); //发送人
        jazMessageDO1.setReceiverId(jazUserOrderDO.getSigningId()); //接收人
        jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_214.getMsg());
        jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_214.getNum());
        jazMessageDO1.setHasSendSms(true);
        jazMessageDO1.setUserOrderId(jazUserOrderDO.getId());
//		jazMessageDO1.setObjectId(jazUserOrderDO.getId());
        jazMessageDO1.setIsRead(0);
        jazMessageService.senMessage(jazMessageDO1);
        // 用户
        JazMessageDO jazMessageDO2 = new JazMessageDO();
        jazMessageDO2.setMessageType(1); //系统消息
        jazMessageDO2.setSenderId(ShiroUtils.getUserId()); //发送人
        jazMessageDO2.setReceiverId(jazUserOrderDO.getInitiateId()); //接收人
        jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_215.getMsg());
        jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_215.getNum());
        jazMessageDO2.setUserOrderId(jazUserOrderDO.getId());
        jazMessageDO2.setHasSendSms(true);
//		jazMessageDO2.setObjectId(jazUserOrderDO.getId());
        jazMessageDO2.setIsRead(0);
        jazMessageService.senMessage(jazMessageDO2);

        return update ? Result.ok() : Result.fail();
    }

    /**
     * 服务列表结束订单
     *
     * @param jazUserOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> endOrder(JazUserOrderDO jazUserOrder) {
        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(jazUserOrder.getId());
        if (jazUserOrderDO == null){
            return Result.fail();
        }
        // 判断订单状态
        if (jazUserOrderDO.getStatus()!=1){
            return Result.fail("订单不是在进行中，不能结束订单");
        }
        // 判断结束时间是否超过过期时间
        if (jazUserOrderDO.getEndTime().getTime()<new Date().getTime()){
            return Result.fail("服务订单已结束不能结束订单");
        }

        jazUserOrderDO.setStatus(2); //订单状态已完成
        jazUserOrderDO.setConcludeStatus(4);

        boolean update = jazUserOrderService.updateById(jazUserOrderDO);

        //旧的月嫂未上户
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>()
                .eq("sys_userid",jazUserOrderDO.getSigningId()));
        if (jazUserAuntDO == null){
            throw new RuntimeException();
        }
        jazUserAuntDO.setSigningStatus(0); //待签约
        jazUserAuntDO.setFamilyStatus(0); // 未上户
        boolean update1 = jazUserAuntService.updateById(jazUserAuntDO);
        if (!update1){
            throw new RuntimeException();
        }

        // 发送消息  阿姨
        JazMessageDO jazMessageDO1 = new JazMessageDO();
        jazMessageDO1.setMessageType(1); //系统消息
        jazMessageDO1.setSenderId(ShiroUtils.getUserId()); //发送人
        jazMessageDO1.setReceiverId(jazUserOrderDO.getSigningId()); //接收人
        jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_217.getMsg());
        jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_217.getNum());
        jazMessageDO1.setHasSendSms(true);
        jazMessageDO1.setUserOrderId(jazUserOrderDO.getId());
//		jazMessageDO1.setObjectId(jazUserOrderDO.getId());
        jazMessageDO1.setIsRead(0);
        jazMessageService.senMessage(jazMessageDO1);
        // 用户
        JazMessageDO jazMessageDO2 = new JazMessageDO();
        jazMessageDO2.setMessageType(1); //系统消息
        jazMessageDO2.setSenderId(ShiroUtils.getUserId()); //发送人
        jazMessageDO2.setReceiverId(jazUserOrderDO.getInitiateId()); //接收人
        jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_216.getMsg());
        jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_216.getNum());
        jazMessageDO2.setUserOrderId(jazUserOrderDO.getId());
        jazMessageDO2.setHasSendSms(true);
//		jazMessageDO2.setObjectId(jazUserOrderDO.getId());
        jazMessageDO2.setIsRead(0);
        jazMessageService.senMessage(jazMessageDO2);

        return update ? Result.ok() : Result.fail();
    }

    /**
     * 阿姨端查询订单详情
     * @param id
     * @return
     */
    @Override
    public JazUserOrderVO auntOrderDetail(Long id) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        //查询出订单信息
        JazUserOrderVO jazUserOrderVO = new JazUserOrderVO();
        JazUserOrderDO jazUserOrderDO = this.selectById(id);
        BeanUtils.copyProperties(jazUserOrderDO,jazUserOrderVO);
        jazUserOrderVO.setStartTime(sf.format(jazUserOrderDO.getStartTime()));
        jazUserOrderVO.setEndTime(sf.format(jazUserOrderDO.getEndTime()));

        if(jazUserOrderDO.getOrderType()==2){
            //查询服务类型
            JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserOrderDO.getProjectId());
            jazUserOrderVO.setProjectName(jazSysProjectDO.getName());
        }

        return jazUserOrderVO;
    }

    /**
     * 查询首页收入/订单信息
     * type 0 根据开始时间和结束时间过滤 1 今日  2 当月
     * @return
     */
    @Override
    public OrderRechargeVo  getOrderRecharge(Integer type,String startTime,String endTime) {
        // 定义日期格式器
       // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 获取当前日期和月份的格式化字符串
        String currentDateStr = sdf.format(new Date());
        String currentMonthStr = currentDateStr.substring(0, 7); // 提取月份部分
        //团购订单
        List<JazGroupOrderDO> orderIncomes = Optional.ofNullable(jazGroupOrderService
                .selectList(new EntityWrapper<JazGroupOrderDO>()
                        .eq("wx_status","支付成功"))).orElse(new ArrayList<>());
        // 课程订单
        List<JazCoursesOrderDO> courseIncomes = Optional.ofNullable(jazCoursesOrderDao
                .selectList(new EntityWrapper<JazCoursesOrderDO>()
                        .eq("status","支付成功"))).orElse(new ArrayList<>());
        //课程收入
        BigDecimal courseIncome=new BigDecimal(0);
        //团购收入
        BigDecimal groupIncome=new BigDecimal(0);
        //商品收入
        BigDecimal commodityIncome=new BigDecimal(0);
        //课程数量
        Integer courseNum=0;
        //团购数量
        Integer groupNum=0;
        //商品数量
        Integer commodityNum=0;
        // 总收入
        BigDecimal grossIncome=new BigDecimal(0);
        // 总数量
        Integer totalOrderNum=0;
        // 判断类型
        if (type==1 || type==null){
            // 查询当天的数据
            return getOrderRechargeVo(orderIncomes, sdf, currentDateStr, courseIncomes);
        }else if (type==2){
            // 查询当月的数据
            return getRechargeVo(orderIncomes, sdf, currentMonthStr, courseIncomes);
        }else if (type==0){
            return getVo(startTime, endTime, orderIncomes, sdf, courseIncomes);
        }
        return null;
    }

    /**
     * 查询首页-根据时间段进行查询
     * @param startTime
     * @param endTime
     * @param orderIncomes
     * @param sdf
     * @param courseIncomes
     * @return
     */
    private OrderRechargeVo getVo(String startTime, String endTime, List<JazGroupOrderDO> orderIncomes, SimpleDateFormat sdf, List<JazCoursesOrderDO> courseIncomes) {
        Integer totalOrderNum;
        BigDecimal courseIncome;
        BigDecimal grossIncome;
        Integer commodityNum;
        Integer courseNum;
        BigDecimal commodityIncome;
        BigDecimal groupIncome;
        Integer groupNum;
        // 根据时间段进行查询统计
        if (StringUtil.isNull(startTime) && StringUtil.isNull(endTime)){
            return null;
        }
        // 分组并统计的订单数量
        Map<Integer, List<JazGroupOrderDO>> today = orderIncomes.stream()
                .filter(order -> Objects.nonNull(order.getCreateTime()))
                .filter(order -> {
                    try {
                        return order.getCreateTime().after(sdf.parse(startTime)) && order.getCreateTime().before(sdf.parse(endTime));
                    } catch (Exception e) {
                        return false; // 忽略格式化异常的订单
                    }
                }).collect(Collectors.groupingBy(JazGroupOrderDO::getOrderPayType));
        //获取商品数量
        List<JazGroupOrderDO> jazGroupOrderDOS = today.get(0);
        if (jazGroupOrderDOS!=null) {
            commodityNum=jazGroupOrderDOS.size();
            commodityIncome = Optional.ofNullable(jazGroupOrderDOS.stream().map(JazGroupOrderDO::getShareMoney).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            commodityNum=0;
            commodityIncome =new BigDecimal(0);
        }
        //获取团购数量
        List<JazGroupOrderDO> jazGroupOrderDOS1 = today.get(1);
        if (jazGroupOrderDOS1!=null) {
            groupNum=jazGroupOrderDOS1.size();
            groupIncome = Optional.ofNullable(jazGroupOrderDOS1.stream().map(JazGroupOrderDO::getShareMoney).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            groupNum=0;
            groupIncome =new BigDecimal(0);
        }

        // 课程信息
        // 过滤时间段内订单
        List<JazCoursesOrderDO> todayOrders = courseIncomes.stream()
                .filter(order -> {
                    try {
                        return order.getCreaterDate().after(sdf.parse(startTime)) && order.getCreaterDate().before(sdf.parse(endTime));
                    } catch (Exception e) {
                        return false; // 忽略格式化异常的订单
                    }
                }).collect(Collectors.toList());
        if (todayOrders!=null && todayOrders.size()>0){
            courseNum=todayOrders.size();
            courseIncome=Optional.ofNullable(todayOrders.stream().map(JazCoursesOrderDO::getTotalFee).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            courseNum=0;
            courseIncome =new BigDecimal(0);
        }
        // 总人数
        totalOrderNum=courseNum+groupNum+commodityNum;
        // 总收入
        grossIncome=courseIncome.add(groupIncome).add(commodityIncome).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 用户人数
        Integer userNum =  Optional.ofNullable(userService
                        .selectCount(new EntityWrapper<UserDO>()
                                .between("gmtCreate", startTime, endTime)
                                /*.where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') BETWEEN DATE_FORMAT(startTime,'%Y-%m-%d') AND DATE_FORMAT(endTime,'%Y-%m-%d')")*/
                        ))
                .orElse(0);
        // 新增用户信息
        List<UserDO> userDOList = userService.selectList(new EntityWrapper<UserDO>()
                .between("gmtCreate", startTime, endTime));

        // 阿姨人数
        Integer auntNum =  Optional.ofNullable(jazUserAuntService
                        .selectCount(new EntityWrapper<JazUserAuntDO>()
                                .between("create_time", startTime, endTime)
                                /*.where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') BETWEEN DATE_FORMAT(startTime,'%Y-%m-%d') AND DATE_FORMAT(endTime,'%Y-%m-%d')")*/
                        ))
                .orElse(0);
        // 新增阿姨信息
        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .between("create_time", startTime, endTime));
        // 其他人数  阿姨入住
        Integer houseMovieNum = Optional.of(jazUserHouseDao.selectList(new EntityWrapper<JazUserHouseDO>()
                .eq("audit_status",1).and().in("audit_result",Arrays.asList(0,3))
                .between("create_time", startTime, endTime)
                /*.where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') BETWEEN DATE_FORMAT(startTime,'%Y-%m-%d') AND DATE_FORMAT(endTime,'%Y-%m-%d')")*/
        ).size()).orElse(0);

        // 过滤出用户人数
        // 创建一个Set来存储用户ID，避免重复
        Set<Long> auntIds = new HashSet<>();
        for (JazUserAuntDO aunt : jazUserAuntDOList) {
            auntIds.add(aunt.getSysUserid());
        }

        // 从阿姨列表中移除已经被计算为新增用户的阿姨
        userDOList.removeIf(user -> auntIds.contains(user.getId()));
        userNum=userDOList.size();

        // 总人数
        Integer totalNum=userNum+auntNum+houseMovieNum;

        //月嫂审核数量
        Integer auntSum = Optional.of(jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("audit_status",0)
                .between("create_time", startTime, endTime)
                /*.where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') BETWEEN DATE_FORMAT(startTime,'%Y-%m-%d') AND DATE_FORMAT(endTime,'%Y-%m-%d')")*/
        ).size()).orElse(0);
        //用户需求审核数量
        Integer userSum = Optional.of(jazUserDemandService.selectList(new EntityWrapper<JazUserDemandDO>()
                .eq("audit_status",0)
                .between("create_time", startTime, endTime)
                /*.where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') BETWEEN DATE_FORMAT(startTime,'%Y-%m-%d') AND DATE_FORMAT(endTime,'%Y-%m-%d')")*/
        ).size()).orElse(0);
        // 月嫂住宿审核数
        Integer houseSum = Optional.of(jazUserHouseDao.selectList(new EntityWrapper<JazUserHouseDO>()
                        .eq("audit_status",0)
                        .between("create_time", startTime, endTime)
                        /*.where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') BETWEEN DATE_FORMAT(startTime,'%Y-%m-%d') AND DATE_FORMAT(endTime,'%Y-%m-%d')")*/
                ).size())
                .orElse(0);

        // 团购待审核数
        Integer groupAssignSum = Optional.of(jazUserOrderService.selectList(new EntityWrapper<JazUserOrderDO>()
                        .eq("order_type",1)
                        .isNull("signing_id")
                        .between("create_time", startTime, endTime)
                ).size())
                .orElse(0);

        return new OrderRechargeVo(grossIncome, courseIncome, groupIncome, commodityIncome, totalOrderNum, courseNum,
                groupNum, commodityNum, auntNum, userNum, houseMovieNum, totalNum, auntSum, userSum, houseSum,groupAssignSum);
    }

    /**
     * 查询首页当月的数据
     * @param orderIncomes
     * @param sdf
     * @param currentMonthStr
     * @param courseIncomes
     * @return
     */
    private OrderRechargeVo getRechargeVo(List<JazGroupOrderDO> orderIncomes, SimpleDateFormat sdf, String currentMonthStr, List<JazCoursesOrderDO> courseIncomes) {
        BigDecimal grossIncome;
        BigDecimal courseIncome;
        Integer groupNum;
        BigDecimal groupIncome;
        Integer totalOrderNum;
        Integer commodityNum;
        BigDecimal commodityIncome;
        Integer courseNum;
        // 分组并统计当月的订单数量
        Map<Integer, List<JazGroupOrderDO>> today = orderIncomes.stream()
                .filter(order -> Objects.nonNull(order.getCreateTime()))
                .filter(order -> {
                    try {
                        String orderDateStr = sdf.format(order.getCreateTime());
                        return orderDateStr.startsWith(currentMonthStr);
                    } catch (Exception e) {
                        return false; // 忽略格式化异常的订单
                    }
                })
                .collect(Collectors.groupingBy(JazGroupOrderDO::getOrderPayType));
        //获取商品数量
        List<JazGroupOrderDO> jazGroupOrderDOS = today.get(0);
        if (jazGroupOrderDOS!=null) {
            commodityNum=jazGroupOrderDOS.size();
            commodityIncome = Optional.ofNullable(jazGroupOrderDOS.stream().map(JazGroupOrderDO::getShareMoney).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            commodityNum=0;
            commodityIncome =new BigDecimal(0);
        }
        //获取团购数量
        List<JazGroupOrderDO> jazGroupOrderDOS1 = today.get(1);
        if (jazGroupOrderDOS1!=null) {
            groupNum=jazGroupOrderDOS1.size();
            groupIncome = Optional.ofNullable(jazGroupOrderDOS1.stream().map(JazGroupOrderDO::getShareMoney).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            groupNum=0;
            groupIncome =new BigDecimal(0);
        }

        // 课程过滤当月订单
        List<JazCoursesOrderDO> thisMonthOrders = courseIncomes.stream()
                .filter(order -> {
                    try {
                        String orderDateStr = sdf.format(order.getCreaterDate());
                        return orderDateStr.startsWith(currentMonthStr);
                    } catch (Exception e) {
                        return false; // 忽略格式化异常的订单
                    }
                })
                .collect(Collectors.toList());
        if (thisMonthOrders!=null && thisMonthOrders.size()>0){
            courseNum=thisMonthOrders.size();
            courseIncome=Optional.ofNullable(thisMonthOrders.stream().map(JazCoursesOrderDO::getTotalFee).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            courseNum=0;
            courseIncome =new BigDecimal(0);
        }
        // 总人数
        totalOrderNum=courseNum+groupNum+commodityNum;
        // 总收入
        grossIncome=courseIncome.add(groupIncome).add(commodityIncome).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 用户人数
        Integer userNum =  Optional.ofNullable(userService
                        .selectCount(new EntityWrapper<UserDO>()
                                .where("YEAR(gmtCreate) = YEAR(NOW()) AND MONTH(gmtCreate) = MONTH(NOW())")))
                .orElse(0);
        // 新增用户信息
        List<UserDO> userDOList = userService.selectList(new EntityWrapper<UserDO>()
                .where("YEAR(gmtCreate) = YEAR(NOW()) AND MONTH(gmtCreate) = MONTH(NOW())"));

        // 阿姨人数
        Integer auntNum =  Optional.ofNullable(jazUserAuntService
                        .selectCount(new EntityWrapper<JazUserAuntDO>()
                                .where("YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())")))
                .orElse(0);
        // 新增阿姨信息
        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .where("YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())"));
        // 其他人数  阿姨入住
        Integer houseMovieNum = Optional.of(jazUserHouseDao.selectList(new EntityWrapper<JazUserHouseDO>()
                .eq("audit_status",1).and().in("audit_result",Arrays.asList(0,3))
                .where("YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())")).size()).orElse(0);
        // 过滤出用户人数
        // 创建一个Set来存储用户ID，避免重复
        Set<Long> auntIds = new HashSet<>();
        for (JazUserAuntDO aunt : jazUserAuntDOList) {
            auntIds.add(aunt.getSysUserid());
        }

        // 从阿姨列表中移除已经被计算为新增用户的阿姨
        userDOList.removeIf(user -> auntIds.contains(user.getId()));
        userNum=userDOList.size();

        // 总人数
        Integer totalNum=userNum+auntNum+houseMovieNum;

        //月嫂审核数量
        Integer auntSum = Optional.of(jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("audit_status",0)
                .where("YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())")).size()).orElse(0);
        //用户需求审核数量
        Integer userSum = Optional.of(jazUserDemandService.selectList(new EntityWrapper<JazUserDemandDO>()
                .eq("audit_status",0)
                .where("YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())")).size()).orElse(0);
        // 月嫂住宿审核数
        Integer houseSum = Optional.of(jazUserHouseDao.selectList(new EntityWrapper<JazUserHouseDO>()
                        .eq("audit_status",0)
                        .where("YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())")).size())
                .orElse(0);

        // 团购待审核数
        Integer groupAssignSum = Optional.of(jazUserOrderService.selectList(new EntityWrapper<JazUserOrderDO>()
                        .eq("order_type",1)
                        .isNull("signing_id")
                        .where("YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())")).size())
                .orElse(0);

        return new OrderRechargeVo(grossIncome, courseIncome, groupIncome, commodityIncome, totalOrderNum, courseNum,
                groupNum, commodityNum, auntNum, userNum, houseMovieNum, totalNum, auntSum, userSum, houseSum,groupAssignSum);
    }

    /**
     * 查询首页当天的数据
     * @param orderIncomes
     * @param sdf
     * @param currentDateStr
     * @param courseIncomes
     * @return
     */
    private OrderRechargeVo getOrderRechargeVo(List<JazGroupOrderDO> orderIncomes, SimpleDateFormat sdf, String currentDateStr, List<JazCoursesOrderDO> courseIncomes) {
        BigDecimal grossIncome;
        Integer totalOrderNum;
        Integer commodityNum;
        Integer courseNum;
        BigDecimal groupIncome;
        Integer groupNum;
        BigDecimal courseIncome;
        BigDecimal commodityIncome;
        // 分组并统计今日的订单数量
        Map<Integer, List<JazGroupOrderDO>> today = orderIncomes.stream()
                .filter(order -> Objects.nonNull(order.getCreateTime()))
                .filter(order -> {
                    try {
                        String orderDateStr = sdf.format(order.getCreateTime());
                        return orderDateStr.startsWith(currentDateStr);
                    } catch (Exception e) {
                        return false; // 忽略格式化异常的订单
                    }
                }).collect(Collectors.groupingBy(JazGroupOrderDO::getOrderPayType));
        //获取商品数量
        List<JazGroupOrderDO> jazGroupOrderDOS = today.get(0);
        if (jazGroupOrderDOS!=null) {
            commodityNum=jazGroupOrderDOS.size();
            commodityIncome = Optional.ofNullable(jazGroupOrderDOS.stream().map(JazGroupOrderDO::getShareMoney).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            commodityNum=0;
            commodityIncome =new BigDecimal(0);
        }
        //获取团购数量
        List<JazGroupOrderDO> jazGroupOrderDOS1 = today.get(1);
        if (jazGroupOrderDOS1!=null) {
            groupNum=jazGroupOrderDOS1.size();
            groupIncome = Optional.ofNullable(jazGroupOrderDOS1.stream().map(JazGroupOrderDO::getShareMoney).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            groupNum=0;
            groupIncome =new BigDecimal(0);
        }

        // 课程信息
        // 过滤今日订单
        List<JazCoursesOrderDO> todayOrders = courseIncomes.stream()
                .filter(order -> {
                    try {
                        String orderDateStr = sdf.format(order.getCreaterDate());
                        return orderDateStr.equals(currentDateStr);
                    } catch (Exception e) {
                        return false; // 忽略格式化异常的订单
                    }
                }).collect(Collectors.toList());
        if (todayOrders!=null && todayOrders.size()>0){
            courseNum=todayOrders.size();
            courseIncome=Optional.ofNullable(todayOrders.stream().map(JazCoursesOrderDO::getTotalFee).
                    reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0"));
        }else {
            courseNum=0;
            courseIncome =new BigDecimal(0);
        }
        // 总人数
        totalOrderNum=courseNum+groupNum+commodityNum;
        // 总收入
        grossIncome=courseIncome.add(groupIncome).add(commodityIncome).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 用户人数
        Integer userNum =  Optional.ofNullable(userService
                        .selectCount(new EntityWrapper<UserDO>()
                                .where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')")))
                .orElse(0);
        // 新增用户信息
        List<UserDO> userDOList = userService.selectList(new EntityWrapper<UserDO>()
                .where("DATE_FORMAT(gmtCreate, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')"));
        // 阿姨人数
        Integer auntNum =  Optional.ofNullable(jazUserAuntService
                        .selectCount(new EntityWrapper<JazUserAuntDO>()
                                .where("DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')")))
                .orElse(0);
        // 新增阿姨信息
        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .where("DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')"));
        // 其他人数  阿姨入住
        Integer houseMovieNum = Optional.of(jazUserHouseDao.selectList(new EntityWrapper<JazUserHouseDO>()
                .eq("audit_status",1).and().in("audit_result",Arrays.asList(0,3))
                .where("DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')")).size()).orElse(0);
        // 过滤出用户人数
        // 创建一个Set来存储用户ID，避免重复
        Set<Long> auntIds = new HashSet<>();
        for (JazUserAuntDO aunt : jazUserAuntDOList) {
            auntIds.add(aunt.getSysUserid());
        }

        // 从阿姨列表中移除已经被计算为新增用户的阿姨
        userDOList.removeIf(user -> auntIds.contains(user.getId()));
        userNum=userDOList.size();
        // 总人数
        Integer totalNum=userNum+auntNum+houseMovieNum;

        //月嫂审核数量
        Integer auntSum = Optional.of(jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("audit_status",0)
                .where("DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')")).size()).orElse(0);
        //用户需求审核数量
        Integer userSum = Optional.of(jazUserDemandService.selectList(new EntityWrapper<JazUserDemandDO>()
                .eq("audit_status",0)
                .where("DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')")).size()).orElse(0);
        // 月嫂住宿审核数
        Integer houseSum = Optional.of(jazUserHouseDao.selectList(new EntityWrapper<JazUserHouseDO>()
                        .eq("audit_status",0)
                        .where("DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')")).size())
                .orElse(0);

        // 团购待审核数
        Integer groupAssignSum = Optional.of(jazUserOrderService.selectList(new EntityWrapper<JazUserOrderDO>()
                        .eq("order_type",1)
                        .isNull("signing_id")
                        .where("DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d')")).size())
                .orElse(0);


        return new OrderRechargeVo(grossIncome, courseIncome, groupIncome, commodityIncome, totalOrderNum, courseNum,
                groupNum, commodityNum, auntNum, userNum, houseMovieNum, totalNum, auntSum, userSum, houseSum,groupAssignSum);
    }

    @Override
    public List<JazUserOrderVO> JazUserOrderExcel(JazUserOrderVO jazUserOrderVO) {
        List<JazUserOrderVO> jazUserOrderVOS = jazUserOrderDao.JazUserOrderExcel(jazUserOrderVO);
        return jazUserOrderVOS;
    }

    @Override
    public Result<String> updateByIdStatus(JazUserOrderDO jazUserOrder) {
        boolean  update = jazUserOrderDao.updateByIdStatus(jazUserOrder);
        return  update ? Result.ok() : Result.fail();
    }

    /**
     * 定时更改已到完成时间的订单状态(Scheduled注解)
     * */
    @Scheduled(cron = "0 0/30 * * * ? ")//每天23点执行一次
    public void updateOrderStatus(){
        //查询出结束时间已经超时的订单
        EntityWrapper<JazUserOrderDO>   Wrapper = new EntityWrapper<>();
        Date date = new Date();
        Wrapper.le("end_time", date);//结束时间小于当前时间的订单
        Wrapper.eq("status",1); //进行中的订单
        System.out.println("30分钟执行一次这个定时任务");
        List<JazUserOrderDO> list = jazUserOrderService.selectList(Wrapper);
        //更改已过期的订单状态
        for (int i=0; i < list.size();i++){
            JazUserOrderDO jazUserOrder = new JazUserOrderDO();
            jazUserOrder.setId(list.get(i).getId());
            jazUserOrder.setStatus(2);
            jazUserOrder.setConcludeStatus(4);
            //更改订单状态为已完成
            jazUserOrderService.updateByIdStatus(jazUserOrder);
            JazUserAuntDO jazUserAuntDO = new JazUserAuntDO();
            jazUserAuntDO.setSysUserid(list.get(i).getSigningId());//用户id


            //发起人
            EntityWrapper<JazUserAuntDO> fqrwrapper = new EntityWrapper<JazUserAuntDO>();
            fqrwrapper.eq("sys_userid",list.get(i).getInitiateId());
            fqrwrapper.eq("audit_result","0");
            JazUserAuntDO fqrjazUserAuntDO = jazUserAuntService.selectOne(fqrwrapper);
            if (fqrjazUserAuntDO != null){    //如果 != null表示为月嫂
                //更改月嫂的签约状态
                fqrjazUserAuntDO.setSigningStatus(0);//已签约
                jazUserAuntService.updateById(fqrjazUserAuntDO);
               //查询出对应的月嫂信息
                JazUserAuntDO jazUserAuntDO1 = new JazUserAuntDO();
                jazUserAuntDO1.setId(fqrjazUserAuntDO.getId());
                jazUserAuntDO1.setOrderCount(fqrjazUserAuntDO.getOrderCount() + 1);//完成数量加一
                System.out.println("根据sys_userid月嫂完成单数加一");
                //根据sys_userid月嫂完成单数加一
                jazUserAuntService.updateUserAuntOrderCount(jazUserAuntDO1);
                System.out.println("---------------------------");
            }

            //签约人
            EntityWrapper<JazUserAuntDO> qyrwrapper = new EntityWrapper<JazUserAuntDO>();
            qyrwrapper.eq("sys_userid",list.get(i).getSigningId());
            qyrwrapper.eq("audit_result","0");
            JazUserAuntDO qyrjazUserAuntDO = jazUserAuntService.selectOne(qyrwrapper);
            if (qyrjazUserAuntDO != null){    //如果 != null表示为月嫂
                qyrjazUserAuntDO.setSigningStatus(0);//已签约
                jazUserAuntService.updateById(qyrjazUserAuntDO);
                JazUserAuntDO jazUserAuntDO2 = new JazUserAuntDO();
                jazUserAuntDO2.setId(fqrjazUserAuntDO.getId());
                jazUserAuntDO2.setOrderCount(qyrjazUserAuntDO.getOrderCount() + 1);//完成数量加一
                System.out.println("根据sys_userid月嫂完成单数加一");
                //根据sys_userid月嫂完成单数加一
                jazUserAuntService.updateUserAuntOrderCount(jazUserAuntDO2);
                System.out.println("---------------------------");

            }
//            System.out.println("更改订单状态为已完成");
//            //订单完成后给订单发起人和订单签约人各加200积分
//                //订单发起人加200积分
//                //查询出订单创建人信息
//            UserDO userDO = userService.selectById(list.get(i).getInitiateId());
//            UserDO userDO1 = new UserDO();
//            userDO1.setId(userDO.getId());
//            userDO1.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) + 200));//加200积分
//            userDO1.setAccumulatedPoints(String.valueOf(Double.valueOf(userDO.getAccumulatedPoints()) + 200));
//            //给创建人加积分
//            userService.updateById(userDO1);
//                //订单签约人加200积分
//            UserDO userDOQY = userService.selectById(list.get(i).getSigningId());
//            UserDO userDO2 = new UserDO();
//            userDO2.setId(userDOQY.getId());
//            userDO2.setCurrentPoints(String.valueOf(Double.valueOf(userDOQY.getCurrentPoints()) + 200));//加200积分
//            userDO2.setAccumulatedPoints(String.valueOf(Double.valueOf(userDOQY.getAccumulatedPoints()) + 200));
//            //给签约人加积分
//            userService.updateById(userDO2);
//
//
//            JazUserIntegralDO fqrUserIntegralDO = new JazUserIntegralDO();
//            fqrUserIntegralDO.setIntegralDetail("+200"); //积分
//            fqrUserIntegralDO.setSysUserid(userDO1.getId()); //用户id
//            fqrUserIntegralDO.setIntegralTime(new Date()); //时间
//            fqrUserIntegralDO.setIntegralWay("完成订单"); //用途
//            fqrUserIntegralDO.setCurrentIntegral(userDO1.getCurrentPoints()); //当前积分
//            jazUserIntegralService.insert(fqrUserIntegralDO);
//
//            JazUserIntegralDO qyrUserIntegralDO = new JazUserIntegralDO();
//            qyrUserIntegralDO.setIntegralDetail("+200"); //积分
//            qyrUserIntegralDO.setSysUserid(userDO2.getId()); //用户id
//            qyrUserIntegralDO.setIntegralTime(new Date()); //时间
//            qyrUserIntegralDO.setIntegralWay("完成订单"); //用途
//            qyrUserIntegralDO.setCurrentIntegral(userDO2.getCurrentPoints()); //当前积分
//            jazUserIntegralService.insert(qyrUserIntegralDO);
        }
    }

    /**
     *定时器待开始的订单到时间了状态改为进行这种
     * */
    @Scheduled(cron = "0 0/5 * * * ? ")//每隔三十分钟执行一次//cron = "0 0/30 * * * ? "//fixedRate= 3000//3000毫秒刷新一次
    public Result<String>  updateOrderStatus2(){
        //查询出开始时间已到的订单
        EntityWrapper<JazUserOrderDO>   Wrapper = new EntityWrapper<>();
        Date date = new Date();
        Wrapper.le("start_time", date);//开始时间小于等当前时间的订单
        Wrapper.gt("end_time",date);//结束时间大于等于当前时间的订单
        Wrapper.eq("status",0); //待开始的订单
        Wrapper.eq("conclude_status",2);//合同签署状态为已签署
        System.out.println("30分钟执行一次这个定时任务2");
        List<JazUserOrderDO> list = jazUserOrderService.selectList(Wrapper);
        //更改订单已经到时间的订单状态
        for (int i=0; i < list.size();i++){
            EntityWrapper<JazUserOrderDO>   Wrapper1 = new EntityWrapper<>();
            Wrapper1.eq("id",list.get(i).getId());
            JazUserOrderDO jazUserOrder = new JazUserOrderDO();
            jazUserOrder.setId(list.get(i).getId());
            jazUserOrder.setStatus(1);//更改订单状态
            //更改订单状态为进行中
//            jazUserOrderService.updateByIdStatus(jazUserOrder);
            jazUserOrderService.updateById(jazUserOrder);
            System.out.println("更改订单状态为进行中");
            //更改月嫂的签约状态
            JazUserAuntDO jazUserAuntDO1 = new JazUserAuntDO();
            jazUserAuntDO1.setSysUserid(list.get(i).getSigningId());//用户id
            jazUserAuntDO1.setSigningStatus(1);//月嫂状态更改为已签约已签约
            jazUserAuntService.updateById(jazUserAuntDO1);
            System.out.println("更改签约状态");
        }
        return  Result.ok();
    }


    /**
     *积分冻结定时器
     *      如果24小时内未产生订单，积分返回至原账户，显示格式为“签约积分返回”
     *       如果24小时产生订单积分正常扣除，显示格式为“完成签约”
     * */
    @Scheduled(cron = "0 0/30 * * * ? ")
    public  void  pointsFrozen(){
        System.out.println("凌晨12点执行订单过期取消扫描");
        Wrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
        Date start = com.jinzhi.jzweb.utils.DateUtil.strToDateLong(com.jinzhi.jzweb.utils.DateUtil.dateToStr(new Date(), Locale.CHINA) + " 00:00:00");
        Date end = com.jinzhi.jzweb.utils.DateUtil.strToDateLong(com.jinzhi.jzweb.utils.DateUtil.dateToStr(new Date(), Locale.CHINA) + " 23:59:59");
        wrapper.ge("create_time",start);//开始时间大于等于凌晨12点
        wrapper.lt("create_time",end);//结束时间小于23点59分59秒
        wrapper.eq("conclude_status",1);//签署状态为待签署
        List<JazUserOrderDO> jazUserOrderDOS = jazUserOrderService.selectList(wrapper); //查询出当天的待签署订单
        for (int i=0; i < jazUserOrderDOS.size();i++){
            JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(jazUserOrderDOS.get(i).getId());
            jazUserOrderDO.setConcludeStatus(3);
            jazUserOrderService.updateById(jazUserOrderDO);
            System.out.println("更改合同状态");
//            UserDO getUser = JWTUtil.getUser();
//            UserDO userDO = userService.selectById(jazUserOrderDOS.get(i).getInitiateId());//合同发起人
//            System.out.println("查询出合同发起人信息");
//            //当前积分 + 扣除积分
//            userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) + contractConclude));
//            userService.updateById(userDO);
//            System.out.println("积分回退成功");
//            JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();
//            jazUserIntegralDO.setIntegralDetail("+"+contractConclude); //积分
//            jazUserIntegralDO.setSysUserid(userDO.getId()); //用户id
//            jazUserIntegralDO.setIntegralTime(new Date()); //时间
//            jazUserIntegralDO.setIntegralWay("冻结积分退回"); //用途
//            jazUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
//            jazUserIntegralService.insert(jazUserIntegralDO);
//            System.out.println("积分回退记录");
        }

    }

    /**
     * 随机二十位数字
     * @return
     */
    public static String tweenRandom(){
        // 创建Random对象
        Random random = new Random();
        // 生成20位的随机数字字符串
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 20; i++) {
            // 生成0-9的随机数
            int digit = random.nextInt(10);
            sb.append(digit);
        }
        // 输出随机数
        return sb.toString();
    }

}
